package cn.fuxi2022.module.info.controller;

import cn.fuxi2022.core.utils.JwtUtils;
import cn.fuxi2022.model.empty.applets.GroupStudentInfo;
import cn.fuxi2022.model.resp.R;
import cn.fuxi2022.model.vo.applets.GroupStudentInfoVo;
import cn.fuxi2022.module.info.service.GroupStudentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("user/studentInfo")
public class GroupStudentAppletsController {

    @Autowired
    private GroupStudentInfoService groupStudentInfoService;

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody @Validated GroupStudentInfoVo groupStudentInfoVo, HttpServletRequest httpServletRequest) {

        // 1.获取当前用户Id
        String id = JwtUtils.getMemberIdByJwtToken(httpServletRequest);

        // 2.判断用户是否已经提交
        LambdaQueryWrapper<GroupStudentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GroupStudentInfo::getStudentId, id);
        GroupStudentInfo studentInfo = groupStudentInfoService.getOne(wrapper);

        // 3.已经存在就修改，不存在就再创建
        if (ObjectUtils.isEmpty(studentInfo)) {
            studentInfo = new GroupStudentInfo();
            studentInfo.setStudentId(id);
        }

        // 4.构建对象
        BeanUtils.copyProperties(groupStudentInfoVo, studentInfo);
        // 注意，如果用户是更新信息，那么无需修改它的阶段
        if (ObjectUtils.isEmpty(studentInfo.getIsStudent())||studentInfo.getIsStudent() == 0) {
            studentInfo.setIsStudent(1);
        }

        // 5.插入数据库
        groupStudentInfoService.saveOrUpdate(studentInfo);

        return R.ok("提交成功");
    }

    /**
     * 获取用户信息，判断入社阶段
     */
    @GetMapping("/type")
    public R getType(HttpServletRequest httpServletRequest) {

        // 1.获取当前用户Id
        String id = JwtUtils.getMemberIdByJwtToken(httpServletRequest);

        // 2.获取用户信息
        LambdaQueryWrapper<GroupStudentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GroupStudentInfo::getStudentId, id);
        GroupStudentInfo studentInfo = groupStudentInfoService.getOne(wrapper);

        if (ObjectUtils.isEmpty(studentInfo)){
            return R.ok().data("type",0);
        }

        return R.ok().data("type",studentInfo.getIsStudent());
    }
}
